#ifndef QRSCSERVER_H
#define QRSCSERVER_H

#include <QTcpServer>
#include <QTimer>
#include <QScreen>
#include <QPixmap>
#include <QPointer>
#include <QTcpSocket>
#include <QApplication>
#include <QPainter>

#include <QWidget>
#include <QPushButton>
#include <QComboBox>
#include <QMouseEvent>
#include <QAbstractItemView>
#include <QLineEdit>
#include "basecombobox.h"
#include <QListWidget>
/**
 * @class AsyncScreenshot
 * @brief 实现图片的异步采集
 *
 * 类的详细描述，包括：
 * - 类的主要功能
 * - 设计目的   异步采集桌面图片
 * - 使用场景   在主线程中执行
 * - 重要特性   支持windows、linux平台
 *
 * @note
 * @warning 该类的对象需要在主线程中执行，因为GUI的采集在GUI线程（主线程中）
 * @see
 * @author  dc
 * @date    2025年7月31日
 * @version V1.0
 */
class AsyncScreenshot : public QObject {
    Q_OBJECT
public:
    QPixmap pixmap;
    explicit AsyncScreenshot(QObject *parent = nullptr)
        : QObject(parent) {
        this->moveToThread(qApp->thread()); // 确保在主线程
    }
    ~AsyncScreenshot(){/*qDebug()<<"~AsyncScreenshot";*/}
    void requestScreenshot() {
        //使用槽函数的队列连接，支持跨线程使用
        QMetaObject::invokeMethod(this, "capture", Qt::QueuedConnection);
    }
    void requestMoveMouse(QPoint pos){
        //使用槽函数的队列连接，支持跨线程使用
        QMetaObject::invokeMethod(this, "moveMouse", Qt::QueuedConnection,
                                  Q_ARG(QPoint, pos));
    }
signals:
    void screenshotReady();
private slots:
    void capture() {
        pixmap = captureWithCursor();
        emit screenshotReady();
    }
    QPixmap captureWithCursor() {
        QScreen *screen = QGuiApplication::primaryScreen();
        QPixmap screenshot = screen->grabWindow(0);
        // 添加光标
        QCursor cursor;
        QPoint cursorPos = QCursor::pos();
        QPixmap cursorPixmap;
        cursorPixmap.load(":/img/cursor-line.png");
        QPainter painter(&screenshot);
        painter.drawPixmap(cursorPos+QPoint(-12,-5), cursorPixmap);
        return screenshot;
    }

    void moveMouse(QPoint pos){
        int x = pos.x();
        int y = pos.y();
        // 将鼠标的位置移动
        QCursor::setPos(pos);

        //得到当前获取窗口的坐标
        QWidget *activeWindow = QApplication::activeWindow();
        auto gPos = activeWindow->mapFromGlobal(pos);
        auto item =activeWindow->childAt(gPos);
        if(item == nullptr) return;//qDebug()<<"s-3-1"<<item->metaObject()->className();
        if(BaseComboBox::lastComboBox)
        {
            QPoint targetPos = item->mapFromGlobal(QPoint(x,y));
            QMouseEvent event(QMouseEvent::MouseButtonPress, targetPos,
                              Qt::LeftButton, 0, 0);
            // 向按钮控件发送鼠标点击事件
            qApp->sendEvent(item, &event);

            // 创建完整的鼠标事件序列
            QMouseEvent pressEvent(QEvent::MouseButtonPress, targetPos,
                                   Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);

            // 发送鼠标按下和释放事件
            qApp->sendEvent(item, &pressEvent);

            QKeyEvent enterEvent(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
            qApp->sendEvent(BaseComboBox::lastComboBox->view(), &enterEvent);

            // 5. 处理事件循环
            QCoreApplication::processEvents();

            // 6. 正确关闭下拉框
            BaseComboBox::lastComboBox->hidePopup();

            //BaseComboBox::lastComboBox->hidePopup();
            BaseComboBox::lastComboBox = nullptr;
            return;
        }

        if(item->inherits("QAbstractButton"))
        {
            QAbstractButton *btn = qobject_cast<QAbstractButton *>(item);
            if(btn)
            {
                btn->animateClick();
                return;
            }
        }
        if(item->inherits("QLineEdit"))
        {
            QLineEdit *lineEdit = qobject_cast<QLineEdit *>(item);
            if(lineEdit)
            {
                lineEdit->setFocus();
                QPoint targetPos = item->mapFromGlobal(QPoint(x,y));
                QMouseEvent event(QMouseEvent::MouseButtonRelease, targetPos,
                                  Qt::LeftButton, 0, 0);
                // 向按钮控件发送鼠标点击事件
                qApp->sendEvent(item, &event);
                return;
            }
        }

        // 将鼠标位置转换为目标控件的坐标系
        QPoint targetPos = item->mapFromGlobal(QPoint(x,y));
        QMouseEvent event(QMouseEvent::MouseButtonPress, targetPos,
                          Qt::LeftButton, 0, 0);
        // 向按钮控件发送鼠标点击事件
        qApp->sendEvent(item, &event);
    }//function end
};


struct ClientInfo{
    int srceenIndex;
    bool sendFlag;
    ClientInfo(){
        srceenIndex = 0;
        sendFlag = false;
    }
};

class QRSCServer : public QTcpServer
{
    Q_OBJECT
public:
    explicit QRSCServer(QObject *parent = nullptr);
    ~QRSCServer();
    void setShowPage(QWidget* page){ m_ShowPage = page;}

    void setPort(int port){this->port = port;}
    int getPort(){return port;}

public slots:
    bool startServer(int quality = 20);
    void stopServer();
signals:
    void sigStopServer();
    void sigMoveMouse(QWidget* item,QPoint pos);
protected:
    void sendImage();
    void incomingConnection(qintptr socketDescriptor) override;
private:
    QTimer _caption;
    QHash<QTcpSocket*,ClientInfo> _clientscreen;
    QTcpSocket* _control;
    int _quality;
    QWidget* m_ShowPage;
    int port;
    AsyncScreenshot *screenshot;
};

#endif // QRSCSERVER_H
